#coding=utf-8
import os
from sdsource.web.sina import get_deal
from sdsource.models import Deal

stdeals_dir = '/home/jay/stdeals'

def get_fn(code, exdate):

    d1 = os.path.join(stdeals_dir, code)
    d2 = os.path.join(d1, '%s.csv'%exdate)
    
    return d2
     
def deals2csv(code, exdate, deals):

    fn = get_fn(code, exdate)
    f = open(fn, 'w')
    
    for d in deals:
        s = ','.join([ str(d.time), str(d.price), str(d.volume), d.bors ])
        s = s + '\n'
        f.write(s)
    
    f.close()
    
def download2csv(code, exdate):
    deals2csv(code, exdate, get_deal(code,exdate))

def deal_exists(code, exdate):
    d1 = os.path.join(stdeals_dir, code)
    if not os.path.exists(d1):
        os.mkdir(d1)
        return False
    
    d2 = os.path.join(d1, '%s.csv'%exdate)
    return os.path.exists(d2)
      
def csv2deal(code, exdate):
    fn = get_fn(code, exdate)
    f = open(fn, 'r')
    
    ds = []
    
    lines = f.readlines()
    for line in lines:
        line = line[:-1]
        dd = line.split(',')
        
        d = Deal( dd[0], float(dd[1]),int(dd[2]),dd[3] )
        ds.append(d)
                    
    return ds 




    
   
                    
